package cn._2dland.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import cn._2dland.tools.DamnServlet;
import cn._2dland.utils.HttpUtils;

public class FiftySixServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final String FIFTYSIX_API_URL = "http://vxml.56.com/json/";

    public FiftySixServlet() {
        super();
    }

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String referrer = req.getHeader("Referer");

		String videoUrl = null;
		String duration = null;
		try {
			String vid = req.getParameter("vid");
			if(vid == null || "".equals(vid))
				throw new Exception("无效vid！");

			if(referrer == null) {
				// 读取远程json对象
				String url = FIFTYSIX_API_URL + vid + "/?src=site";
				JSONObject jsonObj = HttpUtils.getHTTPJSONObject(url);
				if(jsonObj == null)
					throw new Exception("获取远程JSON对象失败！");
				// 从json中获取视频信息
				JSONObject vi = jsonObj.getJSONObject("info");
				// 获取视频长度
				duration = vi.getString("duration");
				// 查找清晰视频
				JSONArray flvs = vi.getJSONArray("rfiles");
				for(int i=0; i<flvs.length(); i++) {
					JSONObject flv = flvs.getJSONObject(i);
					String type = flv.getString("type");
					if("normal".equals(type))
						videoUrl = flv.getString("url");
					else if("clear".equals(type)) {
						videoUrl = flv.getString("url");
						break;
					}
				}
			} else {
				videoUrl = new StringBuffer(DamnServlet.DAMN_API_URL).append("?src=56&vid=").append(vid).toString();
				duration = "0";
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			videoUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/parse_failed.flv";
			duration = "5022";
		}

		// 构造视频信息URL
		StringBuffer infoXml = new StringBuffer();
		infoXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"  standalone=\"no\"?>");
		infoXml.append("<video>");
		infoXml.append("<dur>").append(duration).append("</dur>");
		infoXml.append("<url><![CDATA[").append(videoUrl).append("]]></url>");
		infoXml.append("</video>");

		// 返回视频信息
		resp.setContentType("text/xml; charset=UTF-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentLength(infoXml.length());
		resp.getWriter().print(infoXml);
	}
}
